package com.aaa.security;

import com.aaa.entity.ResultData;
import com.aaa.entity.User;
import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

@Component
public class SuccessHandlerConfig implements AuthenticationSuccessHandler {

    /**
     * 认证时，认证成功
     * @param httpServletRequest 请求
     * @param httpServletResponse 响应
     * @param authentication 认证信息
     * @throws IOException
     * @throws ServletException
     */
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("text/json;charset=utf-8");
        System.out.println(authentication);
        // 主要信息：User
        User principal = (User) authentication.getPrincipal();
        System.out.println(principal);

        // 权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        System.out.println(authorities);

        // 密码
        Object credentials = authentication.getCredentials();
        System.out.println(credentials);

        // 详细信息
        Object details = authentication.getDetails();
        int status = httpServletResponse.getStatus();
        System.out.println(status);
        ResultData resultData = new ResultData();
        resultData.setCode(status);
        resultData.setMsg(details.toString());
        resultData.setData(principal.toString());
        System.out.println(resultData.toString());
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(JSON.toJSON(new ResultData(status,details.toString(),principal.toString())));
        writer.flush();
        writer.close();
    }
}
